<template>
  <!-- 全屏加载动画 -->
  <van-overlay :show="checkingLogin" class="loading-overlay">
    <div class="loading-wrapper">
      <van-loading size="24px" color="#9a009a">检查登录状态...</van-loading>
    </div>
  </van-overlay>

  <div class="fw"></div>
  <div class="auth-box" v-if="!checkingLogin">
    <h2>欢迎登录</h2>
    <van-cell-group inset style="margin-bottom: 20px">
      <van-field
          v-model="loginForm.userNumber"
          name="工号"
          label="工&nbsp;&nbsp;&nbsp;&nbsp;号"
          placeholder="请填写工号"
          label-align="left"
          :rules="[{ required: true, message: '请填写工号' }]"
          size="large"
      />
      <van-field
          v-model="loginForm.password"
          type="password"
          name="密码"
          label="密&nbsp;&nbsp;&nbsp;&nbsp;码"
          placeholder="请填写密码"
          label-align="left"
          :rules="[{ required: true, message: '请填写密码' }]"
          size="large"
      />
    </van-cell-group>

    <van-checkbox
        v-model="loginForm.checked"
        checked-color="#ee0a24"
        icon-size="small"
    >
      点击阅读并同意
      <span class="link-text" @click="showBusinessAgreement">《业务开展协议》</span>
      和
      <span class="link-text" @click="showPrivacyAgreement">《隐私协议》</span>
    </van-checkbox>

    <div class="button-container">
      <van-button
          :loading="loginForm.loading"
          :disabled="isLoginDisabled"
          type="primary"
          @click="handleLogin"
      >登录</van-button>
    </div>

    <div class="bottom-links">
      <span class="link-text link_text" @click="switchToRegister">还没有账号？点击注册</span>
      <span class="link-text link_text" @click="switchToReset">忘记密码？</span>
    </div>
  </div>
</template>

<script setup lang="ts" name="LoginView">
import { reactive, computed, ref, onMounted } from 'vue';
import {showDialog, showToast, Overlay, Loading, showSuccessToast, showFailToast} from 'vant';
import { useRouter } from 'vue-router';
import { userLoginUsingPost } from "../../Api/yonghumokuai";
import { useLoginStore } from '../../Store/modules/userinfo/LoginTZ';
import { agreements, AgreementType } from '../../Constants/agreements';
import { useUserStore } from '../../Store/modules/userinfo/UserInfo'

const router = useRouter();
const userStore = useUserStore();
const loginStore = useLoginStore();

// 检查登录状态标志
const checkingLogin = ref(true);

const userTypeText = computed(() => {
  switch(userStore.userInfo?.userType) {
    case 1: return '领导'
    case 2: return '辅导员'
    case 3: return '教师'
    default: return '未知身份'
  }
})

// 切换到注册页面
const switchToRegister = () => {
  loginStore.setActiveTab('register');
};

// 切换到忘记密码页面
const switchToReset = () => {
  loginStore.setActiveTab('reset');
};

// 登录表单
const loginForm = reactive({
  userNumber: '',
  password: '',
  checked: false,
  loading: false
});

// 按钮禁用状态
const isLoginDisabled = computed(() => {
  return !loginForm.userNumber || !loginForm.password || !loginForm.checked;
});

// 显示协议
const showBusinessAgreement = () => showAgreement('business');
const showPrivacyAgreement = () => showAgreement('privacy');

function showAgreement(type: AgreementType) {
  const agreement = agreements[type];
  showDialog({
    title: agreement.title,
    message: agreement.content,
    confirmButtonText: '我已阅读'
  });
}

// 登录处理
async function handleLogin() {
  if (!loginForm.checked) {
    showDialog({ message: '请同意相关协议' })
    return
  }

  loginForm.loading = true
  try {
    const response = await userLoginUsingPost({
      userNumber: loginForm.userNumber,
      password: loginForm.password
    })

    if (response.data.code === 0) {
      const { password, ...userData } = response.data.data // 排除密码字段

      userStore.setUserInfo({
        userId: userData.userId,
        userName: userData.userName,
        userNumber: userData.userNumber,
        userType: userData.userType,
        email: userData.email ?? null,
        department: userData.department ?? null,
        contact: userData.contact ?? null,
        userImage: userData.userImage ?? null
      })

      showSuccessToast('欢迎您！'+  userStore.userInfo.userName)
      await router.push('/cqust/index')
    } else {
      showFailToast(response.data.message || '登录失败')
    }
  } catch (error: any) {
    showDialog({
      message: error.response?.data?.message || '登录失败，请重试！',
    })
  } finally {
    loginForm.loading = false
  }
}

// 检查登录状态
onMounted(async () => {
  try {
    // 等待500ms确保Pinia持久化数据加载完成
    await new Promise(resolve => setTimeout(resolve, 500));

    // 检查用户信息是否存在
    if (userStore.userInfo?.userId) {
      showToast('自动登录中...');
      await router.push('/cqust/index');
    }
  } catch (error) {
    console.error('自动登录检查出错:', error);
  } finally {
    checkingLogin.value = false;
  }
});
</script>

<style scoped>
/* 加载动画样式 */
.loading-overlay {
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: rgba(255, 255, 255, 0.9);
}

.loading-wrapper {
  text-align: center;
}

.loading-wrapper .van-loading {
  margin-bottom: 10px;
}

/*第一层盒子*/
.auth-box {
  width: 82%;
  margin: 0 auto;
  padding: 15px;
  background-color: rgba(255, 255, 255, 0.9);
  border-radius: 8px;
}

.fw {
  height: 20%;
}

/*欢迎登陆*/
h2 {
  font-size: 170%;
  font-weight: 400;
  margin: 30px 15px;
  color: #9a009a;
}

/*阅读协议*/
.link-text {
  color: #747bff;
  cursor: pointer;
}

.link-text:hover {
  text-decoration: none;
}

/*按钮*/
.button-container {
  margin: 20px auto;
  width: 90%;
}

/*按钮*/
:deep(.van-button--primary) {
  width: 100%;
  background-color: #800080;
  border: none;
}

/*按钮显示*/
:deep(.van-button--primary:not(:disabled)) {
  background-color: #800080;
}

/*按钮点击动画*/
:deep(.van-button--primary:not(:disabled):hover) {
  background-color: #9a009a;
}

/*按钮不显示*/
:deep(.van-button--primary:disabled) {
  background-color: rgba(154, 0, 154, 0.98);
  opacity: 0.6;
}

:deep(.van-tab--active) {
  color: #800080;
}

/*按钮下面字样*/
.bottom-links {
  width: 100%;
  margin-top: 3%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 0.9rem;
}

/* 按钮点击效果 */
:deep(.van-button--primary) {
  transition: all 0.2s ease;
}

:deep(.van-button--primary:active) {
  transform: scale(0.98);
}

/* 链接悬停效果 */
.link-text {
  display: inline-block;
  margin: 0 auto;
  transition: all 0.2s ease;
}

.link_text {
  margin: 0;
  padding-left: 5%;
  padding-right: 2%;
}

.link-text:hover {
  opacity: 0.8;
  color: #7c2d7c;
}

/* 复选框动画 */
:deep(.van-checkbox__icon) {
  transition: all 0.2s ease;
}

:deep(.van-checkbox__icon--checked) {
  transform: scale(1.1);
}

/*复选框基础*/
:deep(.van-checkbox) {
  margin-left: 15px;
  font-size: 12px;
}

:deep(.van-button--small:not(:disabled):active) {
  transform: scale(0.95);
}
</style>
